package com.applet.applet_shangcheng.controller;

import com.applet.applet_shangcheng.dao.GoodsMapper;
import com.applet.applet_shangcheng.entity.Address;
import com.applet.applet_shangcheng.entity.Order;
import com.applet.applet_shangcheng.pay.DateUtils;
import com.applet.applet_shangcheng.service.GoodsService;
import com.applet.applet_shangcheng.service.IntegralOrderService;
import com.applet.applet_shangcheng.service.OrderService;
import com.applet.applet_shangcheng.service.UserService;
import com.applet.applet_shangcheng.utlis.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.objects.annotations.Property;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/order")
@CrossOrigin
@Api(value="商城订单管理",tags={"商城订单管理"})
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userServic;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private IntegralOrderService integralOrderService;
    @ApiOperation(value="_根据用户名username查询用户收货地址")
    @GetMapping("/findByAddress/{username}")
    public Result findByAddress(@PathVariable("username") String username) {
        List<Address> addressList = orderService.findByAddress(username);
        if (addressList == null) {
            return new Result(false, StatusCode.ERROR, "您地址为空!");
        }
        return new Result(true, StatusCode.OK, "收货地址查询", addressList);
    }

    @ApiOperation(value="_查询今日商城订单饼图")
    @GetMapping("/getOrderToday")
    public Result getOrderToday() {
        Map<String, Object> map = new HashMap<String, Object>();
        Calendar calendar = Calendar.getInstance();
        String time = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        List<Map<String, Object>> list = orderService.getGoodsNameList(time);
        map.put("goodsNameList", list);
        List<String> setmealNames = new ArrayList<String>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);
        if (list.size() == 0) {
            return new Result(false, StatusCode.ERROR, "今日没有新的订单!", map);
        }
        if (map == null) {
            return new Result(false, StatusCode.ERROR, "今日没有新的订单!");
        }
        return new Result(true, StatusCode.OK, "查询成功", map);
    }

    public static void main(String[] args) {
    }
    @ApiOperation(value="_根据时间查询商城订单饼图")
    @GetMapping("/getOrderTodayS/{datetime}")
    public Result getOrderTodayS(@PathVariable("datetime") String datetime) {
        Map<String, Object> map = new HashMap<String, Object>();
        String years = datetime.substring(0, 4);//年
        String monthd = datetime.substring(datetime.indexOf('-') + 1);
        String monthds1 = monthd.substring(0, 2);//月
        String substring = monthds1.substring(1);
        if (substring.equals("-")) {
            monthds1 = monthds1.substring(0, 1);
        }
        if (!substring.equals("0")) {
            monthds1 = "0" + monthds1;
        }
        String dates = datetime.substring(datetime.lastIndexOf("-") + 1);//日
        String datesS = dates.substring(0, 1);//月
        if (!datesS.equals("0")&&dates.length()<2) {
            dates = "0" + dates;
        }
        String datetimeD = years +"-"+ monthds1+"-" + dates;
        System.out.println(datetimeD);
        List<Map<String, Object>> list = orderService.getGoodsNameList(datetimeD);
        map.put("goodsNameList", list);
        List<String> setmealNames = new ArrayList<String>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);
        if (list.size() == 0) {
            return new Result(false, StatusCode.ERROR, datetime+"今日没有新的订单!", map);
        }
        if (map == null) {
            return new Result(false, StatusCode.ERROR, datetime+"今日没有新的订单!");
        }
        return new Result(true, StatusCode.OK, "查询成功", map);
    }

    @ApiOperation(value="_查询进七天的商城订单")
    @GetMapping("/getOrderTotalNumber")
    public Result getOrderTotalNumber() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> months = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        // 根据当前时间-12，算出12个月之前的时间
        calendar.add(Calendar.DATE, -7);
        for (int i = 1; i <= 7; i++) {
            calendar.add(Calendar.DATE, 1); //12个月之前的时间+1，得到2018-10
            months.add(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
        }
        map.put("months", months);
        List<Integer> hasPay = new ArrayList<>();
        for (String month : months) {
            hasPay.add(orderService.getHasPay(month));
        }
//        List<String>hasPay = orderService.getHasPay();
        map.put("hasPay", hasPay);
        List<Integer> notPay = new ArrayList<>();
        for (String month : months) {
            notPay.add(orderService.getNotPay(month));
        }
        map.put("notPay", notPay);
        if (map == null) {
            return new Result(false, StatusCode.ERROR, "失败");
        }
        return new Result(true, StatusCode.OK, "成功", map);
    }
    @ApiOperation(value="_根据时间段查询商城订单")
    @GetMapping("/getOrderTodayS/{datetime}/{datetime2}")
    public Result getOrderTodayS(@PathVariable("datetime") String datetime,
                                 @PathVariable("datetime2") String datetime2) {
        String years = datetime.substring(0, 4);//年
        String monthd = datetime.substring(datetime.indexOf('-') + 1);
        String monthds1 = monthd.substring(0, 2);//月
        String substring = monthds1.substring(1);
        if (substring.equals("-")) {
            monthds1 = monthds1.substring(0, 1);
        }
        String dates = datetime.substring(datetime.lastIndexOf("-") + 1);//日
        String years2 = datetime2.substring(0, 4);//年
        String monthd2 = datetime2.substring(datetime2.indexOf('-') + 1);
        String monthds = monthd2.substring(0, 2);//月
        String substring2 = monthds.substring(1);
        if (substring2.equals("-")) {
            monthds = monthds.substring(0, 1);
        }
        String dates2 = datetime2.substring(datetime2.lastIndexOf("-") + 1);//日
        System.out.println(years + monthds1 + dates);
        System.out.println(years2 + monthds + dates2);
        Calendar begin = Calendar.getInstance();
        begin.set(Calendar.YEAR, Integer.parseInt(years));
        begin.set(Calendar.MONTH, Integer.parseInt(monthds1) - 1);
        begin.set(Calendar.DATE, Integer.parseInt(dates));
        Calendar end = Calendar.getInstance();
        end.set(Calendar.YEAR, Integer.parseInt(years2));
        end.set(Calendar.MONTH, Integer.parseInt(monthds) - 1);
        end.set(Calendar.DATE, Integer.parseInt(dates2));
        List<String> months = new ArrayList<>();
        while (!end.before(begin)) {
            months.add(new SimpleDateFormat("yyyy-MM-dd").format(begin.getTime()));
            begin.add(Calendar.DATE, 1);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("months", months);
        List<Integer> hasPay = new ArrayList<>();
        for (String month : months) {
            hasPay.add(orderService.getHasPay(month));
        }
//        List<String>hasPay = orderService.getHasPay();
        map.put("hasPay", hasPay);
        List<Integer> notPay = new ArrayList<>();
        for (String month : months) {
            notPay.add(orderService.getNotPay(month));
        }
        map.put("notPay", notPay);
        if (map == null) {
            return new Result(false, StatusCode.ERROR, "失败");
        }
        return new Result(true, StatusCode.OK, "成功", map);
    }
    @ApiOperation(value="_所有商城订单")
    @GetMapping("/getOrder")
    public Result getOrder() {
        List<Order> order = orderService.getOrder();
        if (order == null) {
            return new Result(false, StatusCode.ERROR, "查询失败!");
        }
        return new Result(true, StatusCode.OK, "查询成功", order);
    }
    @ApiOperation(value="_根据id查询商城订单")
    @GetMapping("/getOrderById/{id}")
    public Result getOrderById(@PathVariable("id") int id) {
        Order order = orderService.getOrderById(id);
        if (order == null) {
            return new Result(false, StatusCode.ERROR, "查询失败!");
        }
        return new Result(true, StatusCode.OK, "查询成功", order);
    }

    @ApiOperation(value="_修改商城订单")
    @PostMapping("/updateOrder")
    public Result updateOrder(@RequestBody Order order) {
        order.setUpdateTime(new Date());
        int result = orderService.updateOrder(order);
        if (result > 0) {
            return new Result(true, StatusCode.OK, "修改商品成功");
        }
        return new Result(false, StatusCode.ERROR, "修改商品失败");
    }
    @ApiOperation(value="_分页查询商城订单")
    @PostMapping("/findAll")
    public PageResult findAll(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = orderService.findAll(queryPageBean.getQueryString(), queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        return pageResult;
    }
    //判断推荐码
    @ApiOperation(value="_code根据判断推荐码")
    @PostMapping("/insertOrder/judge")
    public Result insertOrder(@RequestParam(value = "code") String code) {
        String recommendedUserId = userServic.selectCode(code);
        if (StringUtils.isEmpty(recommendedUserId)) {
            return new Result(false, StatusCode.ERROR, "推荐码无效!请重新输入");
        }
        return new Result(true, StatusCode.OK, "有效推荐码");
    }


    /*
    code:推荐码
    consignee:收件人
    consigneeAddress:收货地址
    phone:收件人手机号
    userId:用户id
    goodsId:商品id
    */
    @ApiOperation(value="_创建订单")
    @PostMapping("/insertOrder")
    public Result insertOrder(@RequestParam(value = "code", required = false) String code,
                              @RequestParam(value = "consignee") String consignee,
                              @RequestParam(value = "consigneeAddress") String consigneeAddress,
                              @RequestParam(value = "phone") String phone,
                              @RequestParam(value = "userId") String userId,
                              @RequestParam(value = "goodsId") int goodsId,
                              @RequestParam(value = "number") int number) {
        String recommendedUserId = userServic.selectCode(code);
        if (StringUtils.isEmpty(recommendedUserId)) {
            return new Result(false, StatusCode.ERROR, "推荐码无效!请重新输入");
        }
        if (consignee == null) {
            return new Result(false, StatusCode.ERROR, "收件人不能为空!");
        }
        if (consigneeAddress == null) {
            return new Result(false, StatusCode.ERROR, "收货地址不能为空!");
        }
        if (phone == null && phone.length() > 12) {
            return new Result(false, StatusCode.ERROR, "手机号格式不正确!");
        }
        int i = goodsService.updateNumber(goodsId, number);
        if (i==0){
            return new Result(false, StatusCode.ERROR, "库存不足!");
        }
        try {
            Order order = orderService.insertOrder(code, consignee, consigneeAddress, phone, userId, goodsId, number);
            if (order != null) {
                return new Result(true, StatusCode.OK, "订单添加成功!", order);
            }
            return new Result(true, StatusCode.OK, "订单添加失败!");
        } catch (Exception e) {
            return new Result(false, StatusCode.ERROR, "支付失败!", e.getMessage());
        }
    }
}
